<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/11 18:56
 * Blog：www.myblogs.xyz
 */

namespace app\admin\controller;


use app\common\service\CommonService;
use think\facade\View;

class Admin extends Common
{
    public function index()
    {
        $this->adminList();
        return View::fetch();
    }

    public function agent()
    {
        $keywords  = input('param.keywords','');
        $list_where = [];
        if (!empty($keywords)){
            if (is_mobile($keywords)){
                $list_where['mobile'] = $keywords;
            }else{
                $list_where['account'] = ['like', $keywords . '%'];
            }
        }
        $area_id = input('param.area_id', 0, 'intval');
        if($area_id>0){
            $list_where['area_ids'] = $area_id;
        }
        $list_where['role_id'] = 2;
        $list_where['status'] = 0;
        $admin_model = new \app\common\model\Admin();
        $admin_model->fields = ['province_id,city_id,county_id,city_path,password,pay_pass,last_session_id', true];
        $data = $admin_model->agentLists($list_where, 10, 'create_time desc,admin_id desc');

        View::assign([
            'area_id'=>$area_id,
            'keywords'=>$keywords,
            'count'=>$data['count'],
            'list'=>$data['list'],
            'page'=>$data['page'],
        ]);
        return View::fetch();
    }

    public function selectAdmin()
    {
        $this->adminList(2);
        return View::fetch();
    }

    protected function adminList($state = 0)
    {
        $keywords  = input('param.keywords','');
        $role_id = input('param.role_id', 0, 'intval');
        $admin_id = input('param.admin_id', 0, 'intval');
        $area_id = input('param.area_id', 0, 'intval');
        $list_where = [];
        if (!empty($keywords)){
            if (is_mobile($keywords)){
                $list_where['mobile'] = $keywords;
            }else{
                $list_where['account'] = ['like', $keywords . '%'];
            }
        }
        if (!empty($state)){
            $list_where['role_id'] = 2;
        }else{
            if (!empty($role_id)){
                $list_where['role_id'] = ['in', '1,' . $role_id];
            }
        }
        if (!empty($admin_id)){
            $list_where['admin_pid'] = $admin_id;
        }else{
            $list_where['admin_id|admin_pid'] = $this->adminId;
        }
        if (!empty($area_id)){
            $list_where['area_ids'] = $area_id;
        }
        $list_where['status'] = 0;
        $admin_model = new \app\common\model\Admin();
        $admin_model->fields = ['province_id,city_id,county_id,city_path,password,pay_pass,last_session_id', true];
        $data = $admin_model->adminLists($list_where, 10, 'create_time desc,admin_id desc');
        // 获取代理商人信息
        $admin_list = [];
        if ($this->adminData['role_id'] == 1){
            $admin_model = new \app\common\model\Admin();
            $admin_list = $admin_model->getList(['role_id'=>2], '', 'create_time desc,admin_id desc', 'admin_id,account,nickname');
        }

        View::assign([
            'keywords'=>$keywords,
            'admin_id'=>$admin_id,
            'area_id'=>$area_id,
            'admin_list'=>$admin_list,
            'count'=>$data['count'],
            'list'=>$data['list'],
            'page'=>$data['page'],
        ]);
    }

    public function insertAdmin()
    {
        $this->saveAdmin();
        return View::fetch('save_admin');
    }

    public function updateAdmin()
    {
        $this->saveAdmin();
        return View::fetch('save_admin');
    }

    public function rateAdmin()
    {
        $admin_id = input('param.admin_id', 0, 'intval');
        if (empty($admin_id)){
            $this->redirect('Admin/index', ['p'=>$this->p]);
        }
        $admin_model = new \app\common\model\Admin();
        if (request()->isPost())
        {
            $data = input('post.');
            if (empty($data['admin_id'])){
                $this->returnError('设置失败');
            }
            $rows = $admin_model->where('admin_id', $data['admin_id'])->update($data);
            if (!$rows){
                $this->returnError('设置失败');
            }
            $this->returnSuccess('设置成功');
        }
        $oldData = $admin_model->getFind($admin_id, 'admin_id,is_divide,service_change');
        View::assign([
            'url'=>request()->url(),
            'oldData'=>$oldData
        ]);
        return View::fetch();
    }

    public function looksAdmin()
    {
        $admin_model = new \app\common\model\Admin();
        if (request()->isPost())
        {
            $data = input('post.');
            if (!empty($data['password'])){
                if (empty($data['old_password'])){
                    $this->returnError('请输入旧密码');
                }
                if (empty($data['password'])){
                    $this->returnError('请输入新密码');
                }
                if ($data['old_password'] == $data['password']){
                    $this->returnError('旧密码和新密码不能一致');
                }
                $old_password = $admin_model->getField($this->adminId, 'password');
                if ($old_password != md5($data['old_password'])){
                    $this->returnError('旧密码有误');
                }
                unset($data['old_password']);
                $data['password'] = md5($data['password']);
            }else{
                unset($data['old_password']);
                unset($data['password']);
            }
            $data['last_time'] = NEW_TIME;
            if (!$admin_model->where('admin_id', $this->adminId)->update($data)){
                $this->returnError($admin_model->getError());
            }
            $this->returnSuccess('保存成功');
        }
        $oldData = $admin_model->getFind($this->adminId, 'admin_id,account,nickname,mobile,email');

        View::assign([
            'oldData' => $oldData,
        ]);
        return View::fetch();
    }

    public function saveAdmin()
    {
        $admin_model = new \app\common\model\Admin();
        if (request()->isPost())
        {
            $data = input('post.');
            $data['last_ip'] = get_client_ip();
            $data['last_time'] = NEW_TIME;
            $data['password'] = empty($data['password'])? '' : md5($data['password']);
            // 账户层级 0直属，1下级（仅代理商）
            if ($data['role_id'] == 2){
                $data['level'] = 1;
            }else{
                $data['level'] = 0;
            }
            if (empty($data['mobile'])){
                $this->returnError('请输入绑定手机号');
            }
            if (empty($data[$admin_model->getPk()])){
                if ($admin_model->getExists(['account'=>$data['account']])){
                    $this->returnError('该账户已存在');
                }
                if (empty($data['password'])){
                    $this->returnError('请输入账户密码');
                }
                $data['face'] = 'default.png';
                $data['admin_pid'] = $this->adminId;
                $data['create_time'] = NEW_TIME;
                $data['create_ip'] = get_client_ip();
                if (!$admin_model->operation($data)){
                    $this->returnError($admin_model->getError());
                }
            }else{
                if ($admin_model->getExists(['account'=>$data['account'],'admin_id'=>['neq', $data['admin_id']]])){
                    $this->returnError('该账户已存在');
                }
                if (empty($data['password'])){
                    unset($data['password']);
                }
                if (!$admin_model->operation($data)){
                    $this->returnError($admin_model->getError());
                }
            }
            $this->returnSuccess('保存成功');
        }

        $role_model = new \app\common\model\Role();
        $role_array = $role_model->getList(['admin_id'=>$this->adminId], '', '', 'role_id');
        $role_ids = implode(',', array_merge([3], array_removal($role_array)));
        $role_list = $role_model->getList([['role_id', 'in', $role_ids]]);
        // 获取当前可选区域
        $area_model = new \app\common\model\Area();
        $admin_id = input('param.admin_id', 0, 'intval');
        $oldData = $admin_model->getFind($admin_id);
        if (!empty($oldData)){
            $area_name = [];
            if (!empty($oldData['area_ids'])){
                $area_ids = explode(',', $oldData['area_ids']);
                if (!empty($area_ids)){
                    if (is_array($area_ids)){
                        foreach ($area_ids as $key=>$val){
                            $area_name[] = $area_model->getField($val, 'area_name');
                        }
                    }
                }
            }
            $oldData['area_name'] = implode(',', $area_name);
        }
        $role_id = $this->adminData['role_id'];

        View::assign([
            'oldData'=>$oldData,
            'role_list'=>$role_list,
            'role_id'=>$role_id
        ]);
    }

    public function auditAdmin()
    {
        if (CommonService::audit('state')){
            $this->returnSuccess('操作成功');
        }
        $this->returnError('操作失败');
    }

    public function deleteAdmin()
    {
        if (CommonService::delete()){
            $this->returnSuccess('删除成功');
        }
        $this->returnError('删除失败');
    }
}